// components/ws-form/index.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    formData: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    url: app.globalData.config['url'],
    tempPicPaths: [], // 临时图片路径
    tempFilePaths: [], // 临时文件路径,
    showVoiceGif: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 题选择
    bindQuestionChange(e) {
      if (this.data.formData[e.currentTarget.dataset.index].type === "Radio") {
        let temp = this.data.formData;
        let index = e.currentTarget.dataset.index;
        let optionIdx = e.detail.value;
        for (let h = 0; h < temp[index].options.length; h++) {
          for (let i = 0; i < temp[index].options[h].sonIds.length; i++) {
            for (let j = 0; j < temp.length; j++) {
              if (temp[j].id === temp[index].options[h].sonIds[i]) {
                temp[j].display = (temp[index].options[optionIdx].id === temp[index].options[h].id);
                break;
              }
            }
          }
        }
        temp[index].reply = temp[index].options[optionIdx].value;
        this.setData({
          formData: temp
        })
      } else {
        let str = 'formData[' + e.currentTarget.dataset.index + '].reply';
        this.setData({
          [str]: (e.detail.value instanceof Array) ? e.detail.value.join(',') : e.detail.value
        })
      }
    },

    // 选择地点
    bindSelectAdress(e) {
      var that = this;
      wx.chooseLocation({
        success(res) {
          let str = 'formData[' + e.currentTarget.dataset.index + '].reply';
          that.setData({
            [str]: res.address
          })
        }
      });
    },

    // 开始录音
    bindStartVoice(e) {
      var that = this;
      let index = e.currentTarget.dataset.index;

      const recorderManager = wx.getRecorderManager();
      recorderManager.start();
      that.setData({
        showVoiceGif: true
      })
      recorderManager.onStop((res) => {
        console.log('recorder stop', res)
        that.uploadVoice(res.tempFilePath, index);
        let str = 'formData[' + index + '].tempReply';
        let tempReply = that.data.formData[index].tempReply || [];
        tempReply.push(res.tempFilePath);
        that.setData({
          [str]: tempReply,
          showVoiceGif: false
        })
      })
    },

    // 上传录音
    uploadVoice(voice, index) {
      wx.showLoading({
        title: '上传中...',
        mask: true
      })
      let that = this;
      if (voice.indexOf('wxfile://') > -1 || voice.indexOf('http://tmp') > -1) {
        app.server.uploadVoice(voice).then(function (res) {
          let temp = res.data.url;
          let str = 'formData[' + index + '].reply';
          let reply = that.data.formData[index].reply || [];
          reply.push({
            name: '录音文件-' + temp.substring(temp.length - 14),
            src: temp
          });
          that.setData({
            [str]: reply
          });
          console.log(that.data)
          wx.hideLoading();
        }, function (res) {
          app.showConfirm('提示', '录音上传失败，请重试', false);
          wx.hideLoading();
        });
      }
    },

    bindDeleteVoice(e) {
      let index = e.currentTarget.dataset.index;
      let subIdx = e.currentTarget.dataset.subidx;

      let str1 = 'formData[' + index + '].reply';
      let str2 = 'formData[' + index + '].tempReply';

      let reply = this.data.formData[index].reply;
      let tempReply = this.data.formData[index].tempReply;

      reply.splice(subIdx, 1);
      tempReply.splice(subIdx, 1);

      this.setData({
        [str1]: reply,
        [str2]: tempReply
      })
    },

    // 结束录音
    bindStopVoice() {
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
    },

    // 播放录音
    bindPlayVoice(e) {
      let subIdx = e.currentTarget.dataset.subidx;
      if (this.data.formData[e.currentTarget.dataset.index].reply) {
        const innerAudioContext = wx.createInnerAudioContext();
        innerAudioContext.src = this.data.formData[e.currentTarget.dataset.index].tempReply[subIdx];
        innerAudioContext.onPlay(() => {
          console.log('开始播放')
        })
        innerAudioContext.onError((res) => {
          console.log(res.errMsg)
          console.log(res.errCode)
        })
        innerAudioContext.play();
      }
    },

    //选择图片
    bindSelectImage: function (e) {
      let that = this;
      let index = e.currentTarget.dataset.index;

      wx.chooseImage({
        count: e.currentTarget.dataset.count,
        success: function (res) {
          that.uploadImage(res.tempFilePaths, index);
        },
      })
    },

    // 上传图片
    uploadImage(picList, index) {
      let that = this;
      let temp = [];
      wx.showLoading({
        title: '上传中...',
        mask: true
      })
      for (let i = 0; i < picList.length; i++) {
        if (picList[i].indexOf('wxfile://') > -1 || picList[i].indexOf('http://tmp') > -1) {
          app.server.uploadImage(picList[i]).then(function (res) {
            temp.push(res.data.url)
            if (temp.length == picList.length) {
              let str = 'formData[' + index + '].reply';
              let reply = that.data.formData[index].reply || [];
              reply.push.apply(reply, temp);
              that.setData({
                [str]: reply
              })
              wx.hideLoading();
            }
          }, function (res) {
            app.showConfirm('提示', '图片上传失败，请重试', false);
            wx.hideLoading();
          });
        }
      }
    },

    //浏览图片
    preview: function (e) {
      let index = e.currentTarget.dataset.index;
      let subIndex = e.currentTarget.dataset.subindex;
      let url = this.data.formData[index].reply || [];
      wx.previewImage({
        urls: url,
        current: url[subIndex]
      })
    },

    //删除图片
    deleteImg: function (e) {
      let index = e.currentTarget.dataset.index;
      let subIndex = e.currentTarget.dataset.subindex;
      console.log('-----a-sd-sa-d')
      console.log(e)

      let temp = this.data.formData[index].reply;
      temp.splice(subIndex, 1);

      let str = 'formData[' + index + '].reply';
      this.setData({
        [str]: temp
      })
    },

    // 选择文件
    bindSelectFile(e) {
      var that = this;
      let index = e.currentTarget.dataset.index;
      wx.chooseMessageFile({
        count: e.currentTarget.dataset.count,
        type: 'all', //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
        success(res) {
          for (let i = 0; i < res.tempFiles.length; i++) {
            var size = res.tempFiles[i].size;
            var filename = res.tempFiles[i].filename;
            if (size > 5242880) {
              wx.showToast({
                title: '文件大小不能超过5MB！',
                icon: "none",
                duration: 2000,
                mask: true
              })
              return;
            }
          }
          that.uploadFile(res.tempFiles, index);
        }
      })
    },

    bindDeleteFile(e) {
      let index = e.currentTarget.dataset.index;
      let subIdx = e.currentTarget.dataset.subidx;
      let str = 'formData[' + index + '].reply';
      let reply = this.data.formData[index].reply;
      reply.splice(subIdx, 1);
      this.setData({
        [str]: reply,
      });
    },

    // 上传文件
    uploadFile(fileList, index) {
      let that = this;
      let temp = [];
      wx.showLoading({
        title: '上传中...',
        mask: true
      })
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].path.indexOf('wxfile://') > -1 || fileList[i].path.indexOf('http://tmp') > -1) {
          app.server.uploadFile(fileList[i].path, {
              'filename': fileList[i].name
            })
            .then(function (res) {
              temp.push({
                filename: fileList[i].name,
                url: res.data.url
              })
              if (temp.length === fileList.length) {
                let str = 'formData[' + index + '].reply';
                let reply = that.data.formData[index].reply || [];
                reply.push.apply(reply, temp);
                that.setData({
                  [str]: reply
                })
                wx.hideLoading();
              }
            }, function (res) {
              app.showConfirm('提示', '文件上传失败，请重试', false);
              wx.hideLoading();
            });
        }
      }
    },

    // 提交答卷
    formSubmit() {
      console.log(this.data.formData)
      for (let i = 0; i < this.data.formData.length; i++) {
        if (this.data.formData[i].isMust === '1' && this.data.formData[i].display && !this.data.formData[i].reply) {
          app.showConfirm('提示', this.data.formData[i].name + '不能为空', false);
          return;
        }
      }
      this.triggerEvent("submit", JSON.stringify(this.data.formData));
    }
  }
})